<?php
declare (strict_types=1);

namespace app\common\model;

use think\facade\Cache;

class Cart extends Base
{
    protected $name = 'user_cart';


    public function product()
    {
        return $this->hasOne(Product::class, 'id', 'pid')
            ->field('id,title,price,cate_1,icon,stock');
    }

    public static function add($user, $param): array
    {
        try {
            $product = Product::where(['id' => $param['pid'], 'status' => 1, 'is_del' => 0])->find();
            if (empty($product)) {
                return ['code' => -1, 'msg' => '商品不存在或已下架'];
            }

            // if (!$product->vip_price || $product->vip_price <= 0) {
            //     return ['code' => -1, 'msg' => '商品价格错误'];
            // }
            // $count = parent::where('uid', $user->id)
            //     ->where('shoptype', '<>', $param['shoptype'])->count();
            // if ($count) {
            //     return ['code' => -1, 'msg' => '购物车已有其他产品'];
            // }
            $map['uid'] = $user->id;
            $map['cate_1'] = $product->cate_1;
            $map['pid'] = $param['pid'];
            $map['shoptype'] = $param['shoptype'];
            $map['spce'] = $param['spce'];
            if(!empty($param['seckill_id'])){
                $map['seckill_id'] = $param['seckill_id'];
            }
            $map['price'] = $param['price'];
            $cart = parent::where($map)->find();
            if ($cart) {
                $cart->num = $cart->num + $param['num'];
                $cart->save();
            } else {
                $map['num'] = $param['num'];
                parent::create($map);
            }
            return ['code' => 1, 'msg' => '已添加至购物车'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    public static function edit($type, $id,$num, $uid): array
    {
        try {
            $msg = 'success';
            switch ($type) {
                case 1://加
                    $info = parent::where('id', $id)->find();
                    
                    if ($info->num >= $info->product->stock) {
                        return ['code' => -1, 'msg' => '库存不足'];
                    }
                    if($info['shoptype'] == 'seckill'){
                        $xiangou=SeckillProduct::where([['seckill_id', '=', $info['seckill_id']],['product_id','=',$info['pid']], ['is_del', '=', 0]])->value('num');
                        $sums=parent::where(['uid' => $uid,'pid'=>$info->pid,'shoptype' => 'seckill'])->where([['id','<>',$info->id]])->sum('num');
                        $OrderCount = OrderProduct::where(['uid' => $uid, 'pid' => $info->pid, 'shoptype' => 'seckill'])->sum('num');
                        if(($sums+$OrderCount+$num)>=$xiangou){
                            return ['code' => -1, 'msg' => '该商品每人限购'.$xiangou]; 
                        }else{
                            $info->num = $num;
                        }
                    }else{
                        $info->num = $num;
                        $info->save();
                    }
                    $info->save();
                    break;
                case 2://减
                    //parent::where('id', $id)->dec('num')->update();
                    
                    $info = parent::where('id', $id)->find();
                    $info->num = $num;
                    $info->save();
                    break;
                case 3://删
                    parent::where('id', $id)->delete();
                    $msg = '已删除';
                    break;
                case 4://清空
                    parent::where('uid', $uid)->delete();
                    $msg = '已清空';
                    break;
                case 5://数量变化
                    if ($num < 1) {
                        return ['code' => -1, 'msg' => '数量不能小于1'];
                    }
                    $info = parent::where('id', $id)->find();
                    if ($info->num >= $info->product->stock) {
                        return ['code' => -1, 'msg' => '库存不足'];
                    }

                    parent::where('id', $id)->update(array('num' => $num));
                    $msg = '操作成功';
                    break;
                default:
                    return ['code' => -1, 'msg' => '加载失败'];
            }
            return ['code' => 1, 'msg' => $msg];

        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    //修改购物车商品数量
    public static function cartSaveNum($param, $user){
        try {
            $info=parent::where('id', $param['id'])->find();
            if ($param['num'] > $info->product->stock) {
                return ['code' => -1, 'msg' => '库存不足'];
            }
            if($info->shoptype=='seckill'){
                $xiangou=SeckillProduct::where([['seckill_id', '=', $info['seckill_id']],['product_id','=',$info['pid']], ['is_del', '=', 0]])->value('num');
                // print('<pre>');print_r($xiangou);die;
                $sums=parent::where(['uid' => $user->id,'pid'=>$info->pid,'shoptype' => 'seckill'])->where([['id','<>',$info->id]])->sum('num');
                $OrderCount = OrderProduct::where(['uid' => $user->id, 'pid' => $info->pid, 'shoptype' => 'seckill'])->sum('num');
                if(($sums+$OrderCount+$param['num'])>=$xiangou){
                    return ['code' => -1, 'msg' => '该商品每人限购'.$xiangou]; 
                }else{
                    parent::where('id', $param['id'])->update(['num'=>$param['num']]);
                }
            }else{
                parent::where('id', $param['id'])->update(['num'=>$param['num']]);
            }
            return ['code' => 1, 'msg' => '修改商品数量成功！'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    public static function submit($param, $user): array
    {
        try {
            $all = [];
            foreach ($param['cart_id'] as $k => $v) {
                $spce=parent::where('id', $v)->where('is_del',0)->field('pid,num,cate_1,shoptype,spce,price,seckill_id')->find();
                $stock = Product::where('id', $spce['pid'])->value('stock');
                if ($stock < $spce['num']) {
                    return ['code' => -1, 'msg' => "《" . $v['title'] . "》库存不足！"];
                }
                if($spce['seckill_id'] !=0){
                    $seckill_stock = SeckillProduct::where(['product_id'=>$spce['pid'],'seckill_id'=>$spce['seckill_id']])->value('stock');
                    if($seckill_stock < $spce['num']){
                        return ['code' => -1, 'msg' => "《" . $v['title'] . "》秒杀商品！库存不足！"];
                    }
                }
                $spce['spec']=$spce['spce'];
                $spce['seckill_id']=$spce['seckill_id'];
                $all[$k] = $spce;
            }
            Cache::set('tsOrder_' . $user->id, json_encode($all));
            Cache::set('tsOrderCartIds_' . $user->id, json_encode($param['cart_id']));

            return ['code' => 1, 'msg' => '结算成功'];

        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    public static function clearCart($uid)
    {
        Cache::set('tsOrder_' . $uid, null);
        $ids = Cache::get('tsOrderCartIds_' . $uid);
        if (!empty($ids)) {
            parent::destroy(json_decode($ids, true));
        }
    }

}
